package com.jessechanrui.template.common.template.auth.application.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.jessechanrui.template.common.template.auth.application.service.TenantService;
import com.jessechanrui.template.common.template.auth.common.AuthorizationSupport;
import com.jessechanrui.template.common.template.auth.exception.AuthCenterException;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.AuthCenterFegin;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.authcenter.AuthCenterBaseResponse;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.authcenter.AuthCenterTenant;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.authcenter.CurrentTenantResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author chenrui
 * @version 1.0
 * @description TenantServiceImpl
 * @date 2025/7/18
 */
@Service
@Slf4j
public class TenantServiceImpl implements TenantService {

    @Autowired
    private AuthCenterFegin authCenterFegin;

    @Override
    public void switchTenant(String accessToken, String tenantId) {
        AuthCenterBaseResponse<Object> response = authCenterFegin.switchTenant(accessToken, tenantId);
        if(!response.isSuccess()){
            throw new AuthCenterException("切换租户失败，" + response.getMsg());
        }
    }

    @Override
    public AuthCenterTenant getCurrentTenant(String accessToken) {
        CurrentTenantResponse currentTenantResponse = authCenterFegin.currentTenant(accessToken);
        if (BooleanUtil.isFalse(currentTenantResponse.isSuccess())) {
            throw new AuthCenterException("获取用户租户信息失败");
        }
        return currentTenantResponse.getContent();
    }

    @Override
    public List<AuthCenterTenant> getCurrentTenants() {
        AuthCenterBaseResponse<List<AuthCenterTenant>> response = authCenterFegin.getCurrentTenants(AuthorizationSupport.getCurrentUserToken());
        if(!response.isSuccess()){
            throw new AuthCenterException("获取用户关联租户列表失败，" + response.getMsg());
        }
        return response.getContent();
    }
}
